package com.chunguang.netty.netty.clinet;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class MuClient {
	public MuClient(int size){
		this.size = size;
	}
	
	private int size;
	private Bootstrap bootstrap = new Bootstrap() ;
	private List<Channel> channelList;
	private EventLoopGroup worker;
	private AtomicInteger count = new AtomicInteger() ;
	
	public void init(){
		worker = new NioEventLoopGroup();
		bootstrap.group(worker);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.handler(new ChannelInitializer<Channel>() {

			@Override
			protected void initChannel(Channel ch) throws Exception {
				ch.pipeline().addLast(new StringDecoder());
				ch.pipeline().addLast(new StringEncoder());
				ch.pipeline().addLast(new HiHandler());
				
			}
		});
		channelList = new ArrayList<Channel>();
		for(int i=0;i< size; i++ ){
			 ChannelFuture connect = bootstrap.connect("127.0.0.1", 8000);
			 Channel channel = connect.channel();
			 channelList.add(channel);
		}
		
	}
	public Channel nextChannel(){
		return getChannel(0);
	}
	private Channel getChannel(int i) {
		 
		Channel channel = channelList.get(Math.abs(count.getAndIncrement()%size));
		if (!channel.isActive()) {
			reconnect(channel);
			
			
			
		}
		
		
		
		return channel;
	}
	private void reconnect(Channel channel) {
		synchronized (channel) {
			 if (channelList.indexOf(channel)==-1) {
					return;
			}
			   Channel newChannel = bootstrap.connect("127.0.0.1", 8000).channel();
			 channelList.add(channelList.indexOf(channel),newChannel);
		}
		 
		
	}

}
